package main

import (
	"fmt"
	"log"

	"rdiot-demo/internal/eav/handler"
	"rdiot-demo/internal/shared/config"
	"rdiot-demo/internal/shared/service"
	"rdiot-demo/pkg/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfigDefault()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 初始化日志
	logger, err := utils.NewLogger(cfg.Logger)
	if err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}

	// 连接数据库
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=Asia/Shanghai",
		cfg.Database.Host,
		cfg.Database.User,
		cfg.Database.Password,
		cfg.Database.DBName,
		cfg.Database.Port,
		cfg.Database.SSLMode,
	)

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		logger.Sugar().Fatalf("Failed to connect to database: %v", err)
	}

	// 初始化服务容器
	services := service.NewServices(db, logger)

	// 初始化Gin路由
	router := gin.New()

	// 添加中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	// 注册API路由组
	v1 := router.Group("/api/v1")
	{
		// 注册EAV模块路由
		handler.RegisterRoutes(v1, services.EAVServices, logger)

		// 注册EAV健康检查路由
		handler.RegisterHealthRoutes(v1, services.EAVServices, logger)
	}

	// 启动服务器
	addr := fmt.Sprintf(":%d", cfg.Server.Port)
	logger.Sugar().Infof("Starting server on %s", addr)

	if err := router.Run(addr); err != nil {
		logger.Sugar().Fatalf("Failed to start server: %v", err)
	}
}
